import React,{Component} from 'react';
import { Form, Input, Button, Checkbox, Radio, message } from 'antd';
import { Link, history} from 'react-router-dom';
import './index.less';
import axios from 'axios';
import {connect} from 'react-redux';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
const {TextArea} = Input;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;

class createkey extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			getCode: '',
			value: 1,
		}
	}

	handleSubmit = (e)=>{
		e.preventDefault();
		const _this = this;
		const secretType = this.state.value;
		const Token = localStorage.getItem("token");
		const telPhone = this.state.oldMobile;
		const form = this.props.form;
		const code = form.getFieldValue("code");
		this.props.form.validateFields((err, values) => {
			if(!err){
				var data = {
					secretName: values.keyName,
					secretType: secretType,
					remark: values.remark,
					orgId: this.props.changeOrgid,
				}
				// console.log(data);
				axios({
					method: 'post',
					url: '/api/block/baas/Ca/verifySecretName?secretName='+data.secretName+'&orgId='+this.props.changeOrgid,
				    headers: {
				      'Content-Type': 'application/json',
				      Authorization:Token,
					}
				})
				.then(function(response){
					// console.log(response);
					if(response.data.message == '密钥名称重复，请重新输入'){
						message.warning('密钥名称重复，请重新输入');
					}else{
						axios({
							method: 'get',
							url: '/api/customer/rest/checkMsg?mobile='+ telPhone +'&code='+ code,
			                headers: {
			                  'Content-Type': 'application/json',
			                  Authorization:Token,
		                	}
						})
						.then(function(response){
							if(response.data.data == 'error'){
								message.warning('请输入正确的验证码')
							}else if(response.data.data == 'success'){
								// 此处填写创建密钥接口
								// console.log(data);
								axios({
									method: 'post',
									url: '/api/block/baas/Ca/generatePrivateKey',
									data: data,
					                headers: {
					                  'Content-Type': 'application/json',
					                  Authorization:Token,
				                	}
								})
								.then(function(response){
									// console.log(response)
									if(response.data.code == '200'){
										setTimeout(()=>{
											_this.props.dispatch({
												type: 'changepublickey',
												changepublickey: response.data.data,
											})
											_this.props.dispatch({
												type: 'secretName',
												SecretName: values.keyName
											})
											_this.props.history.push('/certificateManagement/createCertificate');
										})
									}
								})
							}
						})
					}
				})
				.catch(function(error){
					message.error('提交失败')
				})
			}else {
				console.log('Received values of form: ', values);
			}
		})
	}


	handleCode =()=>{
		const _this = this;
		let sec = 60;
		const clickTime = new Date().getTime();
		localStorage.setItem("createKeyclickTime",clickTime);
		const mobile = this.state.oldMobile;
	    const Token = localStorage.getItem("token");
	    if(this.state.getCode !== '获取验证码'){
			return false;
		}
        axios({
          method: 'get',
          url: '/api/customer/rest/sendMsg?mobile='+ mobile,
          headers: {
            'Content-Type': 'application/json',
            Authorization:Token,
          }
        })
        .then(function(response){
          if(response.data.code == '201'){
            message.warning('请输入正确的手机号');
          }else if(response.data.code == '202'){
            message.warning('获取手机验证码失败');
          }else if(response.data.code == '200') {
            const timer = setInterval(function(){
              sec--;
              if(sec < 0){
                clearInterval(timer);
                _this.setState({
                  getCode:  '获取验证码',
                })
                localStorage.setItem("createKeyclickTime","");
              }else {
                _this.setState({
                  getCode:  sec + 's 后重新获取',
                })
              }
            },1000)
          }
        })
	}

	getOrgid =()=>{
		this.props.changeOrgid;
		// setTimeout(()=>{
			// console.log(this.props.changeOrgEnglishName)
		// })
	}
	componentWillUpdate(){
		this.getOrgid();
	}
	componentWillMount(){
		this.getOrgid();
		const _this = this;
		const nowDate = new Date().getTime();
		let sec = localStorage.getItem("createKeyclickTime");
		const currentTime = (nowDate - sec)/1000;
		let delta = Math.round(60 - currentTime);
		const timer = setInterval(function(){
			delta--;
			if(delta < 0){
				clearInterval(timer);
				_this.setState({
					getCode:  '获取验证码',
				})
			}else {
				_this.setState({
					getCode:  delta + 's 后重新获取',
				})
			}
		},1000)
		
		const Token = localStorage.getItem("token");
		axios({
		  method: 'get',
		  url: '/api/customer/user/getTel',
		  headers: {
		    'Content-Type': 'application/json',
		    Authorization:Token,
		  }
		})
		.then(function(response){
		  if(response.data.code == '200'){
		    _this.setState({
		        oldMobile: response.data.data,
		    })
		  }
		})
		.catch(function(error){
		  message.error('获取手机号失败') 
		})
	}

	onChangeRadio = (e) => {
	// console.log('radio checked', e.target.value);
		this.setState({
	  		value: e.target.value,
		});
	}

	// maxLength =(e)=>{
	// 	if(!Number(e.target.value)){
	// 	  message.warning('请输入数字');
	// 	}
	// }			

	render(){
		const { getFieldDecorator } = this.props.form;
		const disabled = this.state.getCode !== '获取验证码' ? "disabled" : "";
		return(
			<div className="subTopBox">
				<div className="subTopBox-hd">
					<div className="hd-title">
						<span className="step active">
							<i>1</i>
						创建秘钥</span>
						<em className="line"></em>
						<span className="step">
							<i>2</i>
						创建证书</span>
						<em className="line"></em>
						<span className="step">
							<i>3</i>
						下载证书</span>
					</div>
				</div>
				<div className="createKey">
					<Form onSubmit={this.handleSubmit}>
						<FormItem
						    label="密钥名称"
						    labelCol={{ span: 5 }}
						    wrapperCol={{ span: 11 }}
						>	
							{getFieldDecorator('keyName',{
								rules: [{required: true, message: '请输入您想创建密钥的名称'}]
							})(
								<Input placeholder="请输入您想创建密钥的名称" />
							)}
							<p className="classTips redColor">* 必填 只能使用英文字母、数字及字符“_”和“-”</p>
						</FormItem>
						<FormItem
						    label="密钥类型"
						    labelCol={{ span: 5 }}
						    wrapperCol={{ span: 11 }}
						>	
							<RadioGroup name="radiogroup" defaultValue={1} onChange={this.onChangeRadio} value={this.state.value}>
					          <Radio value={1}>普通密钥</Radio>
					          <Radio value={2}>高级密钥</Radio>
					        </RadioGroup>
						</FormItem>
						<FormItem
						    label="备注"
						    labelCol={{ span: 5 }}
						    wrapperCol={{ span: 11 }}
						>	
							{getFieldDecorator('remark',{
								rules: [{required: false, message: '请输入对此密钥使用用途等信息的简要描述'}]
							})(
								<TextArea className="textarea" autosize={{ minRows: 5, maxRows: 6 }} placeholder="请输入对此密钥使用用途等信息的简要描述" />
							)}
						</FormItem>
						<FormItem className="namePhone"
						    label="预留手机号"
						    labelCol={{ span: 5 }}
						    wrapperCol={{ span: 11 }}
						>	
							{getFieldDecorator('phone',{
								rules: [{required: false, message: '请输入手机号码'}]
							})(
								<div>
			                        <Input className="phoneText" disabled maxLength={11} value={this.state.oldMobile} />
			                        <Button
							            className="yzmBtn"
							            type= "primary"
							            size="small"
							            // disabled
							            disabled={disabled}
							            onClick = {this.handleCode}
							          >
							          {this.state.getCode}
						        	</Button>
			                    </div> 
							)}
						</FormItem>
						<FormItem
						    label="短信验证码"
						    labelCol={{ span: 5 }}
						    wrapperCol={{ span: 11 }}
						>	
							{getFieldDecorator('code',{
								rules: [{required: true, message: '请输入短信验证码，仅限数字', pattern: /^[0-9]+$/}]
							})(
								<Input type="text" placeholder="请输入短信验证码，仅限数字" maxLength={8} />
							)}
						</FormItem>
						<FormItem
							className="submitBtns"
						    label=" "
						    labelCol={{ span: 5 }}
						    wrapperCol={{ span: 11 }}
						>	
							<div>
								<Link to="/certificateManagement"><Button type="default" className="prevBtn">取消</Button></Link>
								<Button type="primary" htmlType="submit" className="joinBtn">确认创建密钥</Button>
							</div>
						</FormItem>
					</Form>
				</div>
			</div>	
			)
	}
}

const createKey = Form.create()(createkey);
export default connect((state) => {
    return { ...state };
  })(createKey);

